<template>
  <div style="width: 100%; margin: 16px auto; padding: 0 12px;">
    <a-card title="OSS 文件管理">
      <a-space style="margin-bottom:12px; flex-wrap: wrap;" :size="'small'">
        <a-input v-model:value="q" placeholder="Key/URL 关键字" style="width: clamp(200px, 30vw, 360px)" />
        <a-select v-model:value="status" style="width: clamp(160px, 20vw, 240px)" :options="[
          { label: '全部', value: undefined },
          { label: '使用中', value: 1 },
          { label: '未使用', value: 0 }
        ]" allow-clear placeholder="按状态筛选" />
        <a-button type="primary" @click="onSearch">查询</a-button>
        <a-popconfirm v-if="hasPerm('oss:manage')" title="确认清理所有未使用文件？" @confirm="cleanup">
          <a-button danger>清理未使用</a-button>
        </a-popconfirm>
        <SmartUpload v-if="hasPerm('oss:manage')" button-text="上传文件" :multiple="true" :max-count="10" file-type="file" />
        <a-button v-if="hasPerm('oss:manage')" @click="openRefModal">引用查询</a-button>
        <a-button v-if="hasPerm('permission:manage')" @click="openSystemModal">角色/权限</a-button>
      </a-space>
      <a-table :data-source="list" :columns="columns" row-key="id" :loading="loading" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key==='preview'">
            <a-image :src="record.url" :width="80" />
          </template>
          <template v-else-if="column.key==='actions'">
            <a-space>
              <a :href="record.url" target="_blank">打开</a>
              <a v-if="hasPerm('oss:manage') && record.status===0" @click="setStatus(record.url, 1)">设为使用中</a>
              <a v-if="hasPerm('oss:manage') && record.status===1" @click="setStatus(record.url, 0)">设为未使用</a>
              <a v-if="hasPerm('oss:manage')" @click="check(record.key)">校验存在</a>
              <a-popconfirm v-if="hasPerm('oss:manage')" title="确认删除该文件？（会从 OSS 和库中删除）" @confirm="() => del(record.key)"><a>删除</a></a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
      <a-pagination
        :current="pageNo"
        :page-size="pageSize"
        :total="total"
        show-size-changer
        style="margin-top:12px;text-align:right"
        @change="onPageChange"
        @showSizeChange="onSizeChange"
      />
    </a-card>

    <a-modal v-model:open="refModalVisible" :confirm-loading="refLoading" title="引用查询" @ok="loadRefs" ok-text="查询" cancel-text="关闭">
      <a-space direction="vertical" style="width:100%">
        <a-select v-model:value="refType" style="width: 160px" :options="[
          { label: '文章', value: 'article' },
          { label: '简历', value: 'resume' }
        ]" />
        <a-input-number v-model:value="refId" :min="1" :placeholder="refType==='article' ? '文章ID' : '用户ID'" style="width: 200px" />
        <div v-if="!refList.length" class="muted">输入上方条件后点击查询</div>
        <a-list v-else :data-source="refList" bordered>
          <template #renderItem="{ item }">
            <a-list-item>
              <a-image :src="item as string" :width="120" />
              <div style="margin-left:12px;word-break:break-all">
                <a :href="item as string" target="_blank">{{ item }}</a>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-space>
    </a-modal>
    <a-modal v-model:open="sysVisible" title="角色/权限（只读）" :footer="null" width="840px">
      <a-space style="margin-bottom: 12px">
        <a-input v-model:value="sysKeyword" placeholder="关键字(编码/名称/路径)" allow-clear style="width: 260px" />
        <a-button type="primary" @click="loadSystem">查询</a-button>
      </a-space>
      <div style="display:flex; gap:16px">
        <div style="flex:1">
          <h4>角色</h4>
          <a-list :data-source="roles" bordered>
            <template #renderItem="{ item }">
              <a-list-item>{{ (item as any).name }} ({{ (item as any).code }})</a-list-item>
            </template>
          </a-list>
        </div>
        <div style="flex:1">
          <h4>权限</h4>
          <a-list :data-source="perms" bordered>
            <template #renderItem="{ item }">
              <a-list-item>{{ (item as any).code }} <span v-if="(item as any).path"> - {{ (item as any).path }}</span></a-list-item>
            </template>
          </a-list>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import http from '@/api/http'
import type { ApiResponse, PageResponse } from '@/types/api'
import SmartUpload from '@/components/SmartUpload.vue'
import { listRoles, listPermissions } from '@/api/admin/modules/system'
import { usePerm } from '@/composables/usePerm'

interface OssFileVO { id: number; key: string; url: string; status: number; createTime: string }

const loading = ref(false)
const status = ref<number | undefined>(undefined)
const q = ref('')
const list = ref<OssFileVO[]>([])
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)

async function load() {
  loading.value = true
  try {
    const resp = await http.get<ApiResponse<PageResponse<OssFileVO>>>('/admin/oss', { params: { status: status.value, q: q.value || undefined, pageNo: pageNo.value, pageSize: pageSize.value } })
    if (resp.data.code === 0) {
      list.value = resp.data.data.records || []
      total.value = resp.data.data.total || 0
    }
  } finally { loading.value = false }
}

function onSearch() { pageNo.value = 1; load() }
function onPageChange(p: number) { pageNo.value = p; load() }
function onSizeChange(_: number, s: number) { pageSize.value = s; pageNo.value = 1; load() }

async function del(key: string) {
  const resp = await http.delete<ApiResponse<boolean>>('/admin/oss', { params: { key } })
  if (resp.data.code === 0) { message.success('已删除'); load() }
}

async function cleanup() {
  const resp = await http.delete<ApiResponse<number>>('/admin/oss/cleanup')
  if (resp.data.code === 0) { message.success(`已清理 ${resp.data.data} 个文件`); load() }
}

async function setStatus(url: string, st: number) {
  const resp = await http.put<ApiResponse<boolean>>('/admin/oss/status', undefined, { params: { url, status: st } })
  if (resp.data.code === 0) { message.success('已更新状态'); load() }
}

async function check(key: string) {
  const resp = await http.get<ApiResponse<boolean>>('/admin/oss/exists', { params: { key } })
  if (resp.data.code === 0) {
    message.info(resp.data.data ? '对象存在' : '对象不存在')
  }
}

// 引用查询弹窗
const refModalVisible = ref(false)
const refType = ref<'article' | 'resume'>('article')
const refId = ref<number | null>(null)
const refList = ref<string[]>([])
const refLoading = ref(false)
// 系统只读
const sysVisible = ref(false)
const sysKeyword = ref('')
const roles = ref<any[]>([])
const perms = ref<any[]>([])
const { hasPerm } = usePerm()

function openSystemModal() {
  sysVisible.value = true
  loadSystem()
}

async function loadSystem() {
  const [r, p] = await Promise.all([
    listRoles(sysKeyword.value || undefined),
    listPermissions(sysKeyword.value || undefined)
  ])
  if (r.code === 0) roles.value = r.data
  if (p.code === 0) perms.value = p.data
}

function openRefModal() {
  refList.value = []
  refId.value = null
  refType.value = 'article'
  refModalVisible.value = true
}

async function loadRefs() {
  if (!refId.value) { message.warning('请填写ID'); return }
  refLoading.value = true
  try {
    const resp = await http.get<ApiResponse<string[]>>('/admin/oss/references', { params: { type: refType.value, id: refId.value } })
    if (resp.data.code === 0) refList.value = resp.data.data || []
  } finally { refLoading.value = false }
}

const columns = computed(() => [
  { title: '预览', key: 'preview' },
  { title: 'Key', dataIndex: 'key' },
  { title: 'URL', dataIndex: 'url' },
  { title: '状态', dataIndex: 'status', customRender: ({ text }: any) => (text ? '使用中' : '未使用') },
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '操作', key: 'actions' }
])

onMounted(load)
</script>
